<?php
	session_start();
	header("Content-Type: text/html;charset=utf-8");
	if(isset($_GET['code'])){//如果是扫码打开本页面的话并且有对应的事件
		echo "<center>";
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if(strpos($user_agent, 'MicroMessenger') === false) {//判断是否为微信扫码
			echo "<h1>请使用微信扫描二维码</h1>";
			exit();
		}else{//是微信扫码则进行处理
			//创建连接
			$conn = mysqli_connect("localhost", "root", "", "signin");
			mysqli_query($conn,"set names utf8");
			//检测连接
			if (!$conn){
				die("Connection failed:".mysqli_connect_error());
			}
			if(isset($_SESSION['qusername'])&&isset($_SESSION['qevent'])){//如果用户的扫码之前已通过验证(用户名、事件)
				$eventforcheck=$_SESSION['qevent'];
				$nameforcheck=$_SESSION['qusername'];
				$sql = "SELECT * FROM persons WHERE event='$eventforcheck' AND username='start'";//事件启用和事件对的上
				$result = mysqli_query($conn, $sql);
				if($row = mysqli_fetch_assoc($result)){//如果数据库中找到相应的项目说明该事件正在发生，事件是正确的
					$sql = "SELECT * FROM persons WHERE event='$eventforcheck' AND username='$nameforcheck'";
					$result = mysqli_query($conn, $sql);
					if($row = mysqli_fetch_assoc($result)){//如果用户签到的是当前可用的事件
?>
						<title>签到成功！</title>
						<h1><?php echo $_SESSION['qusername']."，你好，你已经在事件“".$_SESSION['qevent']."”中完成了签到！";?></h1>
						<script type="text/javascript" src="js/checkname.js"></script>
						<font color='red'>如需修改名字，请在下方输入：</font>
						<br/><br/>
						<form action="resignin.php" method="POST" onsubmit="return checkname();">
							你的名字：<input maxlength="6" onpaste="return false" onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;" name="signinname" id="signinname" type="text" placeholder="你的名字">
							<br/><br/><input name="提交" type="submit" value="提交">
						</form>
						<script>document.getElementById('signinname').focus();</script>
<?php		
						mysqli_close($conn);
						exit();
					}
				}else{//事件已经结束
					session_destroy();
				}
			}elseif(!isset($_SESSION['qusername'])&&isset($_SESSION['qevent'])){//有扫码但没提交名字
				$eventforcheck=$_SESSION['qevent'];
				$sql = "SELECT * FROM persons WHERE event='$eventforcheck' AND username='start'";//事件启用和事件对的上
				$result = mysqli_query($conn, $sql);
				if($row = mysqli_fetch_assoc($result)){//如果数据库中找到相应的项目说明该事件正在发生，事件是正确的
?>
					<title>扫码成功！</title>
					<script type="text/javascript" src="js/checkname.js"></script>
					<h1><?php echo "你好，你已经在事件“".$_SESSION['qevent']."”中完成了扫码";?><br/><font color="red">但是离签到成功还差一个提交名字</font></h1>
					<font color='red'>输入名字以验证签到：</font>
					<br/><br/>
					<form action="signin.php" method="POST" onsubmit="return checkname();">
						你的名字：<input maxlength="6" onpaste="return false" onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;" name="signinname" id="signinname" type="text" placeholder="你的名字">
						<br/><br/><input name="提交" type="submit" value="提交">
					</form>
					<script>document.getElementById('signinname').focus();</script>
<?php
					mysqli_close($conn);
					exit();
				}else{//事件已经结束
					session_destroy();
				}
			}
			//此次事件还没扫码过
			$usercode=$_GET['code'];
			$usercode = mysqli_real_escape_string($conn,$usercode);
			$sql = "SELECT * FROM persons WHERE code='$usercode' AND username='start'";//事件启用并且code和事件均对的上
			$result = mysqli_query($conn, $sql);
			if(!$row = mysqli_fetch_assoc($result)){//如果数据库中没找到相应的项目说明签到失败
				mysqli_close($conn);
				echo "<title>签到失败</title>";
				echo "<h1>签到失败，可能是签到已经结束了</h1>";
				exit();
			}
			//获取code和时间
			$code=$usercode;//user的code与事件是匹配的，接下来验证时间
			$lasttime=$row['add_time'];
			$ys=time()-$lasttime;//获取延时
		}
		echo "延时了：".$ys."s<br/>";
		if(($ys<=30)&&($code==$_GET['code'])){
			$_SESSION['isscan']=1;//成功签到
			$_SESSION['keywords']=$code;
			$_SESSION['qevent']=$row['event'];//保存这次签到的事件
			echo "<title>扫码成功！</title>";
			echo "扫码成功！";
			if($ys<10){
				echo "<br/>速度好快啊，厉害！";
			}elseif($ys<25){
				echo "<br/>速度一般，还行！";
			}else{
				echo "<br/>好险，差点没赶上！";
			}
?>
			<script type="text/javascript" src="js/checkname.js"></script>
			<br/><br/><h1><font color='red'>输入名字以验证签到：</font></h1>
			<br/><br/>
			<form action="signin.php" method="POST" onsubmit="return checkname();">
				你的名字：<input maxlength="6" onpaste="return false" onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;" name="signinname" id="signinname" type="text" placeholder="你的名字">
				<br/><br/><input name="提交" type="submit" value="提交">
			</form>
			<script>document.getElementById('signinname').focus();</script>
			<script>setTimeout(function() {alert('扫码成功，请输入名字以验证签到！');},1000)</script>
<?php
			mysqli_close($conn);
			exit();
		}else{
			echo "<title>扫码失败！</title>";
			echo "扫码失败！";
			echo "<br/>不好意思，你是上一趟的吧！";
			echo "<br/><font color='red'>下次快点点进来吧！</font>";
			mysqli_close($conn);
			exit();
		}		
	}else{//不是扫码界面
?>
<!DOCTYPE html>
<html>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>扫码签到<?php if(isset($_SESSION['thisevent'])) echo '--'.$_SESSION['thisevent'];?></title>
    <link type="text/css" href="bootstrap.min.css" rel="stylesheet">       
    <script src="js/jquery-1.10.2.min.js"></script>
	<script>
		function checkLeave(){
			event.returnValue="请正常退出签到系统！（通过点击结束签到来退出）";
		}
	</script>
</head>
<body class="indexbody"<?php if(isset($_SESSION['thisevent'])) echo ' onbeforeunload="checkLeave()"';?>>
	<div class="container">
	<?php if(isset($_SESSION['thisevent'])) echo '<center><h1>'.$_SESSION['thisevent'].'</h1></center>';?>
		<div class="panel panel-sm" style="box-shadow:0 0px 0px;">
				<div class="tab-content" style="padding-top: 15px;">
					<div role="tabpanel" class="tab-pane fade in active" id="pane1" aria-labelledby="tab1">
						<div class="form-group form-group-sm">
							<label class="control-label col-md-2">二维码内容</label>
							<div class="col-md-10">
								<textarea name="txtContent" id="txtContent" rows="2" class="form-control input-normal" placeholder="http://<?php echo $_SERVER['HTTP_HOST'];echo $_SERVER['REQUEST_URI'];?>?code=000000" readonly></textarea>
							</div>
						</div>
						<p>&nbsp;</p>
						<div class="form-group form-group-sm">
							<label class="control-label col-md-2">二维码图像</label>
							<div class="col-md-10">
								<div id="qrcode">
									<div style="margin:auto;width:300px;min-height:150px;color:green;float:right;" id="show">签到成功的名字将显示在这里</div>
								</div>
								<p class="m-top-10 text-muted">使用微信扫一扫</p>
								<p>刷新倒计时 <font color="red" id="countdown">0</font></p>
								<p><font color="red">扫完之后一定要输入名字才能完成签到哦！！！</font></p>
								<?php
									if(isset($_SESSION['quid'])){
										echo '<a href="adminlogin.php?type=logout">结束签到</a>';
									}else{
										echo '<a href="adminlogin.php">激活签到系统</a>';
									}
								?>
							</div>
						</div>
						
						<div class="form-group form-group-sm">
							<div class="col-md-10 col-md-offset-2">
								<p class="form-control-static text-danger" id="tips"></p>
							</div>
						</div>
					</div>
				</div>
				
		</div>
	</div>
    <script src="js/modernizr-2.8.3.js" type="text/javascript"></script>
    <script src="js/bootstrap.min.js" type="text/javascript"></script>    
    <script type="text/javascript" src="js/qrcode.min.js"></script>
	<script type="text/javascript">
		var wait = 30;
		var txtContent = document.getElementById("txtContent"), tips = $("#tips");
		var qrcode = new QRCode('qrcode', {
			text: 'http://<?php echo $_SERVER['HTTP_HOST'];echo $_SERVER['REQUEST_URI'];?>?code=000000',
			width: 300,
			height: 300,
			colorDark: '#000000',
			colorLight: '#ffffff',
			correctLevel: QRCode.CorrectLevel.H
		});
		function getXmlHttpObject(){
			var xmlHttpRequest;
			if(window.ActiveXObject){
				xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
			}else{
				xmlHttpRequest=new XMLHttpRequest();
			}
			return xmlHttpRequest;
		}
		function getCode(){
			var myXmlHttpRequest="";
			myXmlHttpRequest=getXmlHttpObject();
			if(myXmlHttpRequest){
				var url="getnewcode.php";
				myXmlHttpRequest.open("post",url,true);
				myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				myXmlHttpRequest.onreadystatechange=function (){
					if(myXmlHttpRequest.readyState==4){
						if(myXmlHttpRequest.status==200){
							document.getElementById("txtContent").value="http://<?php echo $_SERVER['HTTP_HOST'];echo $_SERVER['REQUEST_URI'];?>?code="+myXmlHttpRequest.responseText;
							if(myXmlHttpRequest.responseText=="000000"){
								alert("对不起，还未登录，无法使用扫码签到！");
							}else if(myXmlHttpRequest.responseText=="000001"){
								alert("对不起，活动还没开始或已被结束！");
							}else if(myXmlHttpRequest.responseText=="000002"){
								alert("对不起，当前活动已改变，请重新登录！");
								location.href="adminlogin.php";
							}else{
								loadXMLDoc();
								freshCode();
							}
						}
					}
				}
				myXmlHttpRequest.send();
			}
		}
		function loadXMLDoc()
		{
			var myXmlHttpRequest="";
			myXmlHttpRequest=getXmlHttpObject();
			if(myXmlHttpRequest){
				var url="signined.php";
				myXmlHttpRequest.open("post",url,true);
				myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				myXmlHttpRequest.onreadystatechange=function (){
					if(myXmlHttpRequest.readyState==4){
						if(myXmlHttpRequest.status==200){
							document.getElementById("show").innerHTML=myXmlHttpRequest.responseText;
						}
					}
				}
				myXmlHttpRequest.send();
			}
		}
		function freshCode(){
			qrcode.clear();
			tips.empty();
			qrcode.makeCode(txtContent.value);
			wait = 30;
			time(document.getElementById("countdown"));
		}
		function time(o){
			o.innerHTML = wait;
			if (wait == 0){
				getCode();
			}else{ 
				wait--;
				setTimeout(function() {
					time(o)
				},
				1000)
			}
		}
		getCode();
	</script>
</body>
</html>	
<?php
	}
?>